package com.mszlu.news.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mszlu.news.admin.mapper.*;
import com.mszlu.news.admin.model.params.ArticleParam;
import com.mszlu.news.admin.pojo.Article;
import com.mszlu.news.admin.pojo.ArticleBody;
import com.mszlu.news.admin.pojo.ArticleTag;
import com.mszlu.news.admin.pojo.Category;
import com.mszlu.news.admin.service.ArticleService;
import com.mszlu.news.admin.vo.ArticleVo;
import com.mszlu.news.admin.vo.Result;
import com.mszlu.news.admin.vo.TagVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class ArticleServiceImpl implements ArticleService {
    @Autowired
    private ArticleMapper articleMapper;
    @Autowired
    private CommentMapper commentMapper;
    @Autowired
    private CollectMapper collectMapper;
    @Autowired
    private GoodMapper goodMapper;
    @Autowired
    private ComplainMapper complainMapper;
    @Autowired
    private CategoryMapper categoryMapper;

    @Override
    public Result selectArticle(ArticleParam articleParam) {
        Page<ArticleVo> articlePage=new Page<>(articleParam.getPage(),articleParam.getPageSize());
        IPage<ArticleVo> articleIPage=articleMapper.selectArticle(articlePage,articleParam.getId(),articleParam.getSummary(),articleParam.getTitle(),articleParam.getAccount(),articleParam.getContent(),articleParam.getCategoryName(),articleParam.getTags());
        List<ArticleVo> records = articleIPage.getRecords();
        List<ArticleVo> articleVos=copyList(records, true);
        articleIPage.setRecords(articleVos);
//        return Result.success(copyList(records, true));
        return Result.success(articleIPage);
    }

    @Autowired
    private ArticleTagMapper articleTagMapper;
    @Autowired
    private ArticleBodyMapper articleBodyMapper;

    @Override
    public Result addArticle(ArticleParam articleParam) {
        Article article = new Article();
//        article.setAuthorId(sysUser.getId());
        article.setAuthorId(articleParam.getAuthorId());
        article.setWeight(Article.Article_Common);
        article.setViewCounts(0);
        article.setTitle(articleParam.getTitle());
        article.setSummary(articleParam.getSummary());
        article.setCommentCounts(0);
        article.setCreateDate(System.currentTimeMillis());
        article.setCategoryId(Long.parseLong(articleParam.getCategory().getId()));
        article.setCollectCounts(0);
        article.setGoodCounts(0);

        article.setPreimg(articleParam.getPreimg());
        //插入之后 会生成一个文章id
        this.articleMapper.insert(article);
        //tag
        List<TagVo> tags = articleParam.getTags();
        if (tags != null) {
            for (TagVo tag : tags) {
                Long articleId = article.getId();
                ArticleTag articleTag = new ArticleTag();
                articleTag.setTagId(Long.parseLong(tag.getId()));
                articleTag.setArticleId(articleId);
                articleTagMapper.insert(articleTag);
            }
        }
        //body
        ArticleBody articleBody = new ArticleBody();
        articleBody.setArticleId(article.getId());
        articleBody.setContent(articleParam.getBody().getContent());
        articleBody.setContentHtml(articleParam.getBody().getContentHtml());
        articleBodyMapper.insert(articleBody);

        article.setBodyId(articleBody.getId());
        articleMapper.updateById(article);
        Map<String, String> map = new HashMap<>();
        map.put("id", article.getId().toString());
        return Result.success(map);
    }

    @Override
    public Result updateArticle(ArticleParam articleParam) {
        Article article = new Article();
//        article.setAuthorId(sysUser.getId());
        article.setAuthorId(articleParam.getAuthorId());
        article.setId(articleParam.getId());
        article.setWeight(Article.Article_Common);
        article.setTitle(articleParam.getTitle());
        article.setSummary(articleParam.getSummary());
        article.setCreateDate(System.currentTimeMillis());
        article.setCategoryId(Long.parseLong(articleParam.getCategory().getId()));
        article.setPreimg(articleParam.getPreimg());

        articleMapper.updateById(article);
        //tag
        List<TagVo> tags = articleParam.getTags();
        if (tags != null) {
            LambdaQueryWrapper<ArticleTag> tagLambdaQueryWrapper=new LambdaQueryWrapper<>();
            tagLambdaQueryWrapper.eq(ArticleTag::getArticleId,articleParam.getId());
            articleTagMapper.delete(tagLambdaQueryWrapper);
            for (TagVo tag : tags) {
                Long articleId = article.getId();
                ArticleTag articleTag = new ArticleTag();
                articleTag.setTagId(Long.parseLong(tag.getId()));
                articleTag.setArticleId(articleId);
                articleTagMapper.insert(articleTag);
            }
        }
        //body
//        ArticleBody articleBody = new ArticleBody();
//        articleBody.setArticleId(articleParam.getId());
//        articleBody.setContent(articleParam.getBody().getContent());
//        articleBody.setContentHtml(articleParam.getBody().getContentHtml());
//        articleBodyMapper.updateById(articleBody);
        UpdateWrapper<ArticleBody> updateWrapper=new UpdateWrapper<>();
        updateWrapper.eq("article_id",articleParam.getId());
        ArticleBody articleBody = new ArticleBody();
        articleBody.setContent(articleParam.getBody().getContent());
        articleBody.setContentHtml(articleParam.getBody().getContentHtml());
        articleBodyMapper.update(articleBody,updateWrapper);

        article.setBodyId(articleBody.getId());
        articleMapper.updateById(article);
        Map<String, String> map = new HashMap<>();
        map.put("id", article.getId().toString());
        return Result.success(map);
    }

    @Override
    public Result deleteArticleById(Long articleId) {
        articleMapper.deleteById(articleId);
        Map<String,Object> map=new HashMap<>();
        map.put("article_id",articleId);
        commentMapper.deleteByMap(map);
        collectMapper.deleteByMap(map);
        goodMapper.deleteByMap(map);
        complainMapper.deleteByMap(map);
        articleBodyMapper.deleteByMap(map);
        articleTagMapper.deleteByMap(map);
        return Result.success("文章删除成功");
    }

    @Override
    public Result hotArticle(int limit) {
        LambdaQueryWrapper<Article> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByDesc(Article::getViewCounts);
        queryWrapper.select(Article::getId,Article::getTitle,Article::getSummary,Article::getViewCounts,Article::getGoodCounts,Article::getPreimg);
        queryWrapper.last("limit " + limit);
        //select id,title from article order by view_counts desc limit 5
        List<Article> articles = articleMapper.selectList(queryWrapper);

        return Result.success(articles);
    }


    @Override
    public Result viewArticle() {
        QueryWrapper<Article> articleQueryWrapper=new QueryWrapper<>();
        articleQueryWrapper.select("sum(view_counts) as viewCounts","category_id");
        articleQueryWrapper.groupBy("category_id");
        List<Article> articles=articleMapper.selectList(articleQueryWrapper);
        for (Article article : articles){
            article.setCategoryName(categoryMapper.selectById(article.getCategoryId()).getCategoryName());
        }
        return Result.success(articles);
    }

    @Override
    public Result topArticle(ArticleParam articleParam) {
        Article article=new Article();
        article.setWeight(articleParam.getWeight());
        article.setId(articleParam.getId());
        articleMapper.updateById(article);
        return Result.success("修改置顶成功");
    }


    private ArticleVo copy(ArticleVo articleVo, boolean isTag) {
//        ArticleVo articleVo = new ArticleVo();
//        articleVo.setId(String.valueOf(article.getId()));
//        BeanUtils.copyProperties(article, articleVo);
//
//        articleVo.setCreateDate(new DateTime(article.getCreateDate()).toString("yyyy-MM-dd HH:mm"));
        if (isTag) {
//            Long articleId = article.getId();
            Long articleId = Long.valueOf(articleVo.getId());
            List<TagVo> tags = articleMapper.findTagsByArticleId(articleId);
            articleVo.setTags(tags);
        }
        return articleVo;
    }

    private List<ArticleVo> copyList(List<ArticleVo> records, boolean isTag) {
        List<ArticleVo> articleVoList = new ArrayList<>();
        for (ArticleVo record : records) {
            articleVoList.add(copy(record, isTag));
        }
        return articleVoList;
    }

}
